<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
    <!--  <el-form-item label="工单编码" prop="workNumber">
        <el-input
          v-model="queryParams.workNumber"
          placeholder="请输入工单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目代码" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="工单名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入工单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择工单类型" class="width_100" @change="handleQuery">
          <el-option v-for="item in orderTypeList" :key="item.dictCode" :label="item.dictValue" :value="item.dictCode">
          </el-option>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="计划完成时间" prop="planTime">
        <el-date-picker clearable
          v-model="queryParams.planTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择计划完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理人" prop="dealPerson">
        <el-input
          v-model="queryParams.dealPerson"
          placeholder="请输入处理人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单来源" prop="origin">
        <el-input
          v-model="queryParams.origin"
          placeholder="请输入工单来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--<el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workOrder:leftProblem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workOrder:leftProblem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workOrder:leftProblem:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['workOrder:leftProblem:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="leftProblemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单编号" align="center" prop="workNumber" width="140" />
<!--      <el-table-column label="项目代码" align="center" prop="projectCode" width="130" />-->
      <el-table-column label="工单名称" align="center" prop="name"/>
      <el-table-column label="工单类型" align="center" prop="type" width="230">
        <template slot-scope="scope">
          <span>{{ orderTypeObject[scope.row.type]}}</span>
        </template>
      </el-table-column>
<!--       <el-table-column label="工单内容" align="center" prop="contents" /> -->
      <el-table-column label="计划完成时间" align="center" prop="planTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="dealPerson" width="80">
        <template slot-scope="scope">
          <span v-if="dealPersonList.indexOf(scope['row']['dealPerson']) != '-1'">{{ personObject[scope.row.dealPerson]
          }}</span>
          <span v-else>{{ scope.row.dealPerson }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="处理记录" align="center" prop="dealLog" /> -->
      <el-table-column label="状态" align="center" prop="status" width="140">
        <template slot-scope="scope">
          <el-tag type="danger">已关闭</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="工单来源" align="center" prop="origin" width="180"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="230px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="check(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改遗留问题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="工单编号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工单编号" :disabled="checkDisabled || editDisabled" />
        </el-form-item>
        <el-form-item label="工单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入工单名称" :disabled="checkDisabled" />
        </el-form-item>
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择工单类型" class="width_100" :disabled="checkDisabled">
            <el-option v-for="item in orderTypeList" :key="item.dictCode" :label="item.dictValue" :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单内容" prop="contents">
          <el-input v-model="form.contents" type="textarea" placeholder="请输入内容" :disabled="checkDisabled" />
        </el-form-item>
        <el-form-item label="计划完成时间" prop="planTime">
          <el-date-picker clearable :disabled="checkDisabled" v-model="form.planTime" type="date"
            value-format="yyyy-MM-dd" style="width: 100%" placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="处理人" prop="dealPerson">
           <el-input v-model="form.dealPerson" placeholder="请输入处理人" />
         </el-form-item>-->
        <el-form-item label="处理记录" prop="dealLog">
          <el-input v-model="form.dealLog" type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" placeholder="请输入内容" :disabled="checkDisabled"/>
        </el-form-item>
        <!--<el-form-item label="工单来源" prop="origin">
          <el-input v-model="form.origin" placeholder="请输入工单来源" />
        </el-form-item>-->
        <!-- <el-form-item label="工单附件上传" prop="orderFile">
          <el-upload
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            :action="uploadUrl"
            :on-success="handleSuccess"
            :show-file-list="true"
            multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="工单附件上传" prop="orderFile">
          <!-- 文件列表 -->
          <div class="upload-file-list el-upload-list el-upload-list--text">
            <div :key="file.url" class="el-upload-list__item ele-upload-list__item-content"
              v-for="(file, index) in fileList" style="display: flex; justify-content: space-between">
              <el-link :underline="false" >
                <span class="el-icon-document" @click="downloadFile(file.url, file.name)"> {{ file.name }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action" v-if="!checkDisabled">
                <el-link :underline="false" @click="handleDeleteFile(file, index)" type="danger">删除</el-link>
              </div>
            </div>
          </div>
          <el-upload v-if="!checkDisabled" class="upload-demo" :headers="{ Authorization: Authorization }"
            :action="uploadUrl" :data="{ workNumber: form.workNumber, projectCode: currentProject }" name="file"
            :on-success="handleSuccess" :show-file-list="false" :file-list="fileList">
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="处理过程附件上传" prop="processFile">
          <div class="upload-file-list el-upload-list el-upload-list--text">
            <div :key="file.url" class="el-upload-list__item ele-upload-list__item-content"
              v-for="(file, index) in fileProcessList" style="display: flex; justify-content: space-between">
              <el-link :underline="false" >
                <span class="el-icon-document" @click="downloadFile(file.url, file.name)"> {{ file.name }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action" v-if="!checkDisabled">
                <el-link :underline="false" @click="handleProcessDelete(file, index)" type="danger">删除</el-link>
              </div>
            </div>
          </div>
          <el-upload v-if="!checkDisabled" class="upload-demo" :headers="{ Authorization: Authorization }"
            :action="uploadUrl" :data="{ workNumber: form.workNumber, projectCode: currentProject }" name="file"
            :file-list="fileProcessList" :on-success="processHandleSuccess" :show-file-list="false" multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.id && checkDisabled" class="table-diy" label="工单流转记录" label-position="left" label-width="100px">
        </el-form-item>
        <el-table v-if="checkDisabled" :data="form.orderLogs" style="width: 100%">
          <el-table-column prop="contents" align="center" label="处理操作" />
          <el-table-column prop="createTime" align="center" label="日期" width="100"/>
          <el-table-column prop="createBy" align="center" label="操作人" width="90"/>
          <el-table-column prop="remark" align="left" label="备注" width="150" />
        </el-table>
      </el-form>
      <!-- <el-form-item label="处理过程附件上传" prop="processFile">
          <el-upload
            class="upload-demo"
            :headers="{Authorization: Authorization}"
            :action="uploadUrl"
            :on-success="processHandleSuccess"
            :show-file-list="true"
            multiple>
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
      </el-form> -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="type != 'view'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLeftProblem,
  getLeftProblem,
  delLeftProblem,
  addLeftProblem,
  updateLeftProblem,
} from "@/api/workOrder/leftProblem";
import { pickupPersonList, orderDetail } from "@/api/workOrder/myOrder";
import { delOrderEnclosure } from "@/api/workOrder/orderEnclosure";
import { getToken } from "@/utils/auth";
import { getDicts } from '@/api/system/dict/data';

export default {
  name: "LeftProblem",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //关闭
      closeVisible: false,
      // 总条数
      total: 0,
      // 遗留问题表格数据
      leftProblemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      orderTypeList: [
     /*   {
          key: "0",
          label: "项目运维工单",
        },
        {
          key: "1",
          label: "系统工单",
        },
        {
          key: "2",
          label: "设备更换工单",
        },
        {
          key: "3",
          label: "需求工单",
        },*/
      ],
      orderTypeObject: {},
      Authorization: "Bearer " + getToken(),
      checkDisabled: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadWorkOrderFile",
      type: "add",
      editDisabled: false,
      username: "",
      personObject: {},
      dealPersonList: [],
      fileList: [],
      fileProcessList: [],
    };
  },
  props: ["currentProject"],
  mounted() {
    this.getList();
    this.getPersonList();
    this.username = this.$store.state.user.name;
    this.getOrderTypeList();
  },
  methods: {
    getOrderTypeList(){
      let oderTypeName = this.currentProject+"_gdlx";
      console.log(oderTypeName)
      getDicts(oderTypeName).then(response => {
        this.orderTypeList= response.data;
        this.transformTypeObject();
      })
    },
    downloadFile(url, fileName) {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';

      xhr.onload = function() {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
          const downloadUrl = URL.createObjectURL(blob);

          const link = document.createElement('a');
          link.href = downloadUrl;
          link.download = fileName;
          link.click();

          URL.revokeObjectURL(downloadUrl);
        }
      };

      xhr.send();
    },
    transformTypeObject() {
      let map = new Map();
      this.orderTypeList.forEach((d) => {
        map.set(d.dictCode, d.dictValue);
      });
      this.orderTypeObject = Object.fromEntries(map);
    },
    /** 查询遗留问题列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectCode = this.currentProject;
      listLeftProblem(this.queryParams).then((response) => {
        this.leftProblemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
      this.fileProcessList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workNumber: null,
        projectCode: null,
        name: null,
        type: null,
        contents: null,
        planTime: null,
        dealPerson: null,
        dealLog: null,
        status: null,
        origin: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.resetForm("form");
      this.checkDisabled = false;
      this.editDisabled = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.type = "add";
      this.title = "添加遗留问题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLeftProblem(id).then((response) => {
        this.form = response.data;
        this.editDisabled = true;
        this.open = true;
        this.type = "edit";
        this.title = "修改遗留问题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.projectCode = this.currentProject;
          if (this.form.id != null) {
            updateLeftProblem(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeftProblem(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("删除后将同步删除工单内附件，确认删除？")
        .then(function () {
          return delLeftProblem(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workOrder/leftProblem/export",
        {
          ...this.queryParams,
        },
        `leftProblem_${new Date().getTime()}.xlsx`
      );
    },
    //工单附件上传
    handleSuccess(res, file) {
      console.log(file);
    },
    //处理过程附件上传
    processHandleSuccess(res, file) {
      console.log(file);
    },
    //查看
    check(id) {
      // getLeftProblem(id).then(response => {
      //     this.form = response.data;
      //     this.open = true;
      //     this.type = 'view';
      //     this.title = "查看遗留问题";
      //     this.checkDisabled = true;
      // });
      orderDetail(id).then((response) => {
        // console.log("调用查看方法,调用接口返回的数据为:",response)
        this.form = response.data;
        for (const oderType of this.orderTypeList) {
          if (this.form.type==oderType.dictCode){
            this.form.type=oderType.dictValue;
            break;
          }
        }
        if (
          this.form.orderEnclosureList != null &&
          this.form.orderEnclosureList.length > 0
        ) {
          let files = [];
          let processFiles = [];
          this.form.orderEnclosureList.forEach((d) => {
            if(d.type == 1) {
                files.push(d);
            }else if(d.type != 0) {
                processFiles.push(d);
            }
          });
          this.fileList = files;
          this.fileProcessList = processFiles;
        }
        // 根据工单编号 查询工单下的附件信息
        this.open = true;
        this.type = "view";
        this.title = "查看工单";
        this.checkDisabled = true;
      });
    },
    getPersonList() {
      if (this.currentProject != "") {
        pickupPersonList(this.currentProject).then((res) => {
          if (res.code == 200) {
            let map = new Map();
            res["data"].forEach((d) => {
              map.set(d.userName, d.nickName);
            });
            this.personObject = Object.fromEntries(map);
            this.dealPersonList = Object.keys(this.personObject);
          }
        });
      }
    },
  },
};
</script>
<style scope>
.width_100 {
  width: 100%;
}
</style>
